/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int maxAncestorDiff(TreeNode *root)
    {
        int maxDiff = 0;
        dfsMaxDiff(root, root->val, maxDiff);
        if (root->left != nullptr)
        {
            maxDiff = max(maxDiff, maxAncestorDiff(root->left));
        }
        if (root->right != nullptr)
        {
            maxDiff = max(maxDiff, maxAncestorDiff(root->right));
        }
        return maxDiff;
    }

    void dfsMaxDiff(TreeNode *tree, int rootVal, int &diff)
    {
        diff = max(diff, abs(tree->val - rootVal));
        if (tree->left != nullptr)
        {
            dfsMaxDiff(tree->left, rootVal, diff);
        }
        if (tree->right != nullptr)
        {
            dfsMaxDiff(tree->right, rootVal, diff);
        }
    }
};